﻿Imports System.ComponentModel
Imports System.Drawing.Printing
Imports System.Reflection
Imports DataObject
Imports BusinessObject

Public Class frmBaseCategory

#Region "Declaration"
    Protected sTableName As String 'Biến lưu tên Table của dsThongTinSV được dùng
    Protected sKeyNameID As String ' Tên trường khóa của bảng
    Protected sFormDetailName As String 'Tên form detail cần show
    Protected oRow As DataRow
    Protected oDictionary As New hDBase
    Public tableDictionary As DataTable 'Dung de luu Table hien thoi
    Private iPosition As Integer = 0
    Private sKeyValue As System.Guid
    Private sReportID As String = ""
    Private oSavedLayout As Infragistics.Win.UltraWinGrid.UltraGridLayout
    Private sTitle As String

    Public Enum eNumActionMode As Integer
        Edit = 0
        AddNew = 1
        QuickAdd = 2
        Delete = 3
        None = 4
    End Enum

    Public eActionMode As eNumActionMode
#End Region

#Region "Property"

#Region "Form"
    'Tạo thuộc tính truyền vào tên form details
    Public Property FormDetail() As String
        Get
            Return sFormDetailName
        End Get
        Set(ByVal Value As String)
            sFormDetailName = Value
        End Set
    End Property

    'Tạo thuộc tính truyền vào tên bảng trong dsThongTinSV
    Public Property TableName() As String
        Get
            Return sTableName
        End Get
        Set(ByVal Value As String)
            sTableName = Value
        End Set
    End Property

    'Tạo thuộc tính khóa chính của bảng dược dùng
    Public Property TablePrimaryKey() As String
        Get
            Return sKeyNameID
        End Get
        Set(ByVal Value As String)
            sKeyNameID = Value
        End Set
    End Property

#End Region

#End Region

#Region "Function/Sub"
    ''' <summary>
    ''' Hàm chức năng Refresh
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    ''' 
    Public Function RefreshToolbar() As Integer
        Dim intRowCount As Integer = grdList.Rows.VisibleRowCount
        With tbrMain
            .Tools("mnuEdit").SharedProps.Enabled = ListBindingSource.Count > 0
            .Tools("mnuDelete").SharedProps.Enabled = (ListBindingSource.Count > 0)
            .Tools("mnuPrint").SharedProps.Enabled = (ListBindingSource.Count > 0)
        End With
        Return intRowCount
    End Function

    ''' <summary>
    ''' Hàm lấy ra dòng dữ liệu hiện thời
    ''' </summary>
    ''' <param name="oBindingSource">BindingSource</param>
    ''' <returns>Dữ liệu trả về kiểu row (dòng dữ liệu)</returns>
    ''' <remarks></remarks>
    ''' 
    Public Function GetCurrentRow(ByVal oBindingSource As BindingSource) As DataRow
        Dim row As DataRow
        row = CType(oBindingSource.Current, DataRowView).Row
        Return row
    End Function

    Protected Overridable Sub ChangeListBindingSourcePosition()
        If (Not ListBindingSource.IsBindingSuspended) AndAlso (ListBindingSource.Position <> -1) Then
            Dim oRow As DataRow
            oRow = GetCurrentRow(ListBindingSource)
        End If
    End Sub

    Private Function GetFormParameter(ByVal sFormDefinition As String, ByVal iPosition As Integer, Optional ByVal sDefaultValue As String = "") As String
        Try
            Return Split(sFormDefinition, ";")(iPosition - 1)
        Catch ex As Exception
            Return sDefaultValue
        End Try
    End Function

    Private Sub SetRowPositionAfterUpdate()
        If grdList.Rows.Count > 0 Then
            grdList.Selected.Rows.Clear()
            If IsNothing(grdList.ActiveRow) Then
                grdList.Rows(grdList.Rows.Count - 1).Activate()
            End If
            grdList.ActiveRow.Selected = True
        End If
    End Sub
    ''' <summary>
    ''' Hàm thực hiện chức năng hiển thị form detail để tạo dữ liệu mới
    ''' </summary>
    ''' <remarks></remarks>
    Public Overridable Sub AddNew()
        eActionMode = eNumActionMode.AddNew
        ShowFormDetail()
    End Sub
    ''' <summary>
    ''' Hàm thực hiện chức năng hiển thị form detail để sửa dữ liệu
    ''' </summary>
    ''' <remarks></remarks>
    Public Overridable Sub Edit()
        If Not IsNothing(grdList.ActiveRow) AndAlso grdList.ActiveRow.IsDataRow Then
            eActionMode = eNumActionMode.Edit
            ShowFormDetail()
        End If
    End Sub

    ''' <summary>
    ''' Hàm thực hiện chức năng đếm xem có bao nhiêu hàng dữ liệu được chọn để xóa
    ''' </summary>
    ''' <param name="grd"></param>
    ''' <remarks></remarks>
    Public Sub GetRowPositionBeforeDelete(ByRef grd As Infragistics.Win.UltraWinGrid.UltraGrid)
        iPosition = grd.Selected.Rows(0).Index
        For Each oRow As Infragistics.Win.UltraWinGrid.UltraGridRow In grd.Selected.Rows
            If oRow.Index < iPosition Then iPosition = oRow.Index
        Next
    End Sub

    Public Sub SetRowPositionAfterDelete(ByRef grd As Infragistics.Win.UltraWinGrid.UltraGrid)
        Dim iRowCount As Integer = grd.Rows.Count
        If iRowCount > 0 Then
            If iPosition > iRowCount - 1 Then
                iPosition = iRowCount - 1
            End If
            grd.Rows(iPosition).Activate()
            grd.ActiveRow.Selected = True
        End If
    End Sub

#End Region

#Region "Overridles"
    ''' <summary>
    ''' Load dữ liệu vào bảng, hàm này mọi người tự viết
    ''' </summary>
    ''' <remarks></remarks>
    Protected Overridable Sub LoadDataGrid()

    End Sub

    ''' <summary>
    ''' Hàm lấy dữ liệu từ bảng trong CSDL gán vào BindingSource và gán vào lưới hiển thị
    ''' </summary>
    ''' <remarks></remarks>
    Protected Overridable Sub InitData()
        tableDictionary = dsQuanLyHD.Tables(sTableName)
        oDictionary.Connection(sConn)
        With ListBindingSource
            .DataSource = tableDictionary
        End With
        If Not IsNothing(oDictionary) Then
            LoadDataGrid()
        End If
    End Sub

    Protected Overridable Sub InitAddNewRow(ByVal oRow As DataRow)
        With oRow
            .Item(sKeyNameID) = Guid.NewGuid
        End With
    End Sub
    ''' <summary>
    ''' Hàm thực hiện chức năng hiển lấy ra tên form detail tên đầy đủ của form detail (Name và FullName)
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Overridable Function GetFormDetail() As Form
        Dim frm As frmBaseCategoryDetail 'Object
        Dim oFormType As Type
        oFormType = [Assembly].GetExecutingAssembly.GetType(FrmMain.GetType.Namespace + "." + sFormDetailName)
        If Not IsNothing(oFormType) Then
            frm = Activator.CreateInstance(oFormType)
        Else
            frm = Nothing
        End If
        Return frm
    End Function
    ''' <summary>
    ''' Hàm hiển thị form detail và kiểm tra xem hiển thị có binding dữ liệu không
    ''' - Nếu ấn vào nút thêm mới thì không cần binding dữ liệu
    ''' - Nếu ấn vào nút sửa thì dữ liệu cần phải binding theo dòng dữ liệu được chọn
    ''' </summary>
    ''' <remarks></remarks>
    Public Overridable Sub ShowFormDetail()
        Select Case eActionMode
            Case eNumActionMode.AddNew
                oRow = tableDictionary.NewRow
                InitAddNewRow(oRow)
                tableDictionary.Rows.Add(oRow)
                ListBindingSource.MoveLast()
            Case eNumActionMode.Edit
                oRow = GetCurrentRow(ListBindingSource)
        End Select

        Dim ofrm As frmBaseCategoryDetail 'Object
        ofrm = GetFormDetail()
        If Not IsNothing(ofrm) Then
            With ofrm
                .DictionaryObject = oDictionary
                .BindingSource = ListBindingSource
                .RowDetail = oRow
                .ActionMode = eActionMode
                If .ShowDialog() = Windows.Forms.DialogResult.OK Then
                    RefreshToolbar()
                Else
                    ListBindingSource.CancelEdit()
                    ListBindingSource.EndEdit()
                End If
                .Dispose()
            End With
        End If
    End Sub

    Protected Overridable Sub DeleteDictionaryFromGrid()
        grdList.DeleteSelectedRows(False)
    End Sub

    Protected Overridable Function DeleteDictionary() As Boolean

    End Function

    Protected Overridable Sub PrintReport()
        Dim fReport As New frmReport
        Dim dsColumns As DataSet
        Dim iAdjust As Integer

        oSavedLayout = grdList.DisplayLayout.Clone

        dsColumns = dsCollectionColumn()
        fReport.CollectionColumns = dsColumns
        fReport.Title = Me.Text.Trim
        fReport.Title = Me.Text.ToUpper
        If fReport.ShowDialog = Windows.Forms.DialogResult.OK Then
            sTitle = fReport.Title
            CustomizeBeforePrint(fReport.CollectionColumns, iAdjust)
            With pdoc
                .Document = Me.DocumentPrint
                .StartPosition = FormStartPosition.CenterParent
                .WindowState = FormWindowState.Maximized
                .Show()
                .Activate()
            End With
        End If
    End Sub

    Private Function dsCollectionColumn() As DataSet
        Dim ds As New DataSet
        Dim Column As Infragistics.Win.UltraWinGrid.UltraGridColumn
        Dim row As System.Data.DataRow
        Dim i As Integer
        With ds
            .Tables.Add("tbl_DieuChinh")
            .Tables("tbl_DieuChinh").Columns.Add("TenCot", GetType(String))
            .Tables("tbl_DieuChinh").Columns.Add("Chon", GetType(Boolean))
            .Tables("tbl_DieuChinh").Columns.Add("KhoaCot", GetType(String))
            .Tables("tbl_DieuChinh").PrimaryKey = New DataColumn() {.Tables("tbl_DieuChinh").Columns("KhoaCot")}
            Dim iCount As Integer = Me.grdList.DisplayLayout.Bands(0).Columns.Count - 1
            Dim a(iCount) As Integer
            For i = 0 To iCount
                a(i) = grdList.DisplayLayout.Bands(0).Columns(i).Header.VisiblePosition
            Next

            Dim k(iCount) As Integer
            For i = 0 To iCount
                k(i) = a(i)
            Next

            Dim min As Integer = 0
            Dim tem, l As Integer
            For i = 0 To iCount
                min = k(i)
                For l = i + 1 To iCount
                    If k(l) <= k(min) Then
                        min = l
                    End If
                Next
                tem = k(i)
                k(i) = k(min)
                k(min) = tem
            Next

            For i = 0 To iCount
                For l = 0 To iCount
                    If a(l) = k(i) Then
                        Column = Me.grdList.DisplayLayout.Bands(0).Columns(l)
                        If Not Column.Hidden Then
                            row = .Tables("tbl_DieuChinh").NewRow
                            row.Item("TenCot") = Column.Header.Caption
                            row.Item("Chon") = True
                            row.Item("KhoaCot") = Column.Key
                            .Tables("tbl_DieuChinh").Rows.Add(row)
                        End If
                    End If
                Next
            Next

            ds.Tables("tbl_DieuChinh").AcceptChanges()
        End With
        Return ds
    End Function

    Private Sub CustomizeBeforePrint(ByVal ds As DataSet, ByVal intAdJust As Int32)
        Try
            Dim row As System.Data.DataRow
            Dim col As Infragistics.Win.UltraWinGrid.UltraGridColumn

            Dim rowCol As DataRow

            With Me.DocumentPrint
                .Grid = Me.grdList
                .Grid.Dock = DockStyle.None
                .Footer.Appearance.TextHAlign = Infragistics.Win.HAlign.Center
                .Footer.TextLeft = vbCrLf & "In ngày " & Date.Now.Day & "/" & Date.Now.Month & "/" & Date.Now.Year
                .Footer.TextRight = vbCrLf & "Hà Nội, Ngày " & Date.Now.Day & " tháng " & Date.Now.Month & " năm " & Date.Now.Year
                With .Grid.DisplayLayout
                    .Override.Reset()
                    .UseFixedHeaders = False
                    .Appearance.BackColor = Color.White
                    .Appearance.BackColor2 = Color.White
                    .Appearance.Cursor = System.Windows.Forms.Cursors.Hand
                    .Override.AllowRowFiltering = Infragistics.Win.DefaultableBoolean.False
                    .Override.AllowRowSummaries = Infragistics.Win.UltraWinGrid.AllowRowSummaries.False
                    .Override.AllowUpdate = Infragistics.Win.DefaultableBoolean.False
                    .Override.CellClickAction = Infragistics.Win.UltraWinGrid.CellClickAction.RowSelect
                    .Override.HeaderAppearance.BackColor = Color.WhiteSmoke
                    .Override.RowSelectors = Infragistics.Win.DefaultableBoolean.False
                    .Override.HeaderAppearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True
                    .Override.HeaderAppearance.FontData.SizeInPoints = 8
                    .Override.CellMultiLine = Infragistics.Win.DefaultableBoolean.True
                    .Override.RowSizing = Infragistics.Win.UltraWinGrid.RowSizing.AutoFixed
                    .BorderStyle = Infragistics.Win.UIElementBorderStyle.None
                    .Override.BorderStyleCell = Infragistics.Win.UIElementBorderStyle.Solid
                    .Override.BorderStyleRow = Infragistics.Win.UIElementBorderStyle.Solid
                    .Override.BorderStyleHeader = Infragistics.Win.UIElementBorderStyle.Solid
                    .Override.BorderStyleSummaryFooter = Infragistics.Win.UIElementBorderStyle.Solid
                    Select Case intAdJust
                        Case 0
                            .AutoFitStyle = Infragistics.Win.UltraWinGrid.AutoFitStyle.ResizeAllColumns
                        Case 1
                            .AutoFitStyle = Infragistics.Win.UltraWinGrid.AutoFitStyle.ExtendLastColumn
                        Case 2
                            .AutoFitStyle = Infragistics.Win.UltraWinGrid.AutoFitStyle.None
                    End Select
                    'Objective Visible and invisible column
                    For Each col In .Bands(0).Columns
                        rowCol = ds.Tables(0).Rows.Find(col.Key)
                        If Not rowCol Is Nothing Then
                            If rowCol.Item("Chon") = True Then
                                .Bands(0).Columns(col.Key).Hidden = False
                                .Bands(0).Columns(col.Key).Header.Caption = rowCol.Item("TenCot").toUpper
                            Else
                                .Bands(0).Columns(col.Key).Hidden = True
                            End If
                        Else
                            .Bands(0).Columns(col.Key).Hidden = True
                        End If
                    Next

                End With
                .Header.Height = 60
                If sTitle <> "" Then
                    .Header.TextCenter = sTitle
                Else
                    .Header.TextCenter = Me.Text.ToUpper
                End If
                .Header.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True
                .Header.Appearance.FontData.SizeInPoints = 20
            End With
        Catch ex As Exception
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#End Region

#Region "Events"

    Private Sub ListBindingSource_PositionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBindingSource.PositionChanged
        Me.ChangeListBindingSourcePosition()
    End Sub

    Private Sub tbrMain_ToolClick(ByVal sender As System.Object, ByVal e As Infragistics.Win.UltraWinToolbars.ToolClickEventArgs) Handles tbrMain.ToolClick
        Dim sSecureAccessKey As String = GetFormParameter(Me.Tag, 1)
        Try
            Select Case e.Tool.Key
                Case "mnuNew"
                    AddNew()
                    SetRowPositionAfterUpdate()
                    tableDictionary.Clear()
                    LoadDataGrid()
                Case "mnuEdit"
                    Edit()
                    SetRowPositionAfterUpdate()
                    tableDictionary.Clear()
                    LoadDataGrid()
                Case "mnuDelete"
                    DeleteDictionaryFromGrid()
                Case "mnuPrint"
                    PrintReport()
                Case "mnuRefresh"
                    RefreshToolbar()
                    tableDictionary.Clear()
                    LoadDataGrid()
                Case "mnuExit"
                    Me.Close()
            End Select
        Catch ex As Exception
            MessageBox.Show(ex.ToString, "Thông báo lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

    End Sub

    Private Sub grdList_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdList.DoubleClick
        Edit()
        SetRowPositionAfterUpdate()
    End Sub

    Private Sub grdList_AfterRowsDeleted(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdList.AfterRowsDeleted
        Try
            grdList.DeleteSelectedRows(False)
            ListBindingSource.EndEdit()
            DeleteDictionary()
            Me.SetRowPositionAfterDelete(Me.grdList)
            RefreshToolbar()
            tableDictionary.Clear()
            LoadDataGrid()
        Catch ex As Exception
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            tableDictionary.RejectChanges()
        End Try
    End Sub

    Private Sub grdList_BeforeRowsDeleted(ByVal sender As Object, ByVal e As Infragistics.Win.UltraWinGrid.BeforeRowsDeletedEventArgs) Handles grdList.BeforeRowsDeleted
        e.DisplayPromptMsg = False
        Me.GetRowPositionBeforeDelete(Me.grdList)
        If grdList.ActiveRow.IsDataRow Then
            If MessageBox.Show("Bạn thực sự muốn xóa dữ liệu đã chọn không?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
                e.Cancel = True
            End If
        End If
    End Sub
#End Region

End Class




